import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getToken } from '@/utils/auth'

// 基础路由（无需权限）
const basicRoutes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue'),
        meta: { title: '登录', requiresAuth: false }
    },
    {
        path: '/',
        redirect: '/dashboard'
    }
]

// 动态路由（需要权限）
const asyncRoutes: RouteRecordRaw[] = [
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘', icon: 'dashboard', permissions: ['dashboard:view'] }
    },
    {
        path: '/system',
        name: 'System',
        redirect: '/system/user',
        meta: { title: '系统管理', icon: 'setting' },
        children: [
            {
                path: 'user',
                name: 'UserManagement',
                component: () => import('@/views/system/UserManagement.vue'),
                meta: { title: '用户管理', permissions: ['system:user:view'] }
            },
            {
                path: 'role',
                name: 'RoleManagement',
                component: () => import('@/views/system/RoleManagement.vue'),
                meta: { title: '角色管理', permissions: ['system:role:view'] }
            },
            {
                path: 'permission',
                name: 'PermissionManagement',
                component: () => import('@/views/system/PermissionManagement.vue'),
                meta: { title: '权限管理', permissions: ['system:permission:view'] }
            }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes: basicRoutes
})

// 动态添加路由
export const addAsyncRoutes = (permissions: string[]) => {
    const filteredRoutes = filterAsyncRoutes(asyncRoutes, permissions)

    // 添加Layout包装
    const layoutRoute: RouteRecordRaw = {
        path: '/',
        name: 'Layout',
        component: () => import('@/views/Layout.vue'),
        children: filteredRoutes,
        meta: { requiresAuth: true }
    }

    router.addRoute(layoutRoute)

    // 404页面
    router.addRoute({
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/404.vue')
    })
}

// 过滤异步路由
const filterAsyncRoutes = (routes: RouteRecordRaw[], permissions: string[]): RouteRecordRaw[] => {
    const filteredRoutes: RouteRecordRaw[] = []

    routes.forEach(route => {
        const tempRoute = { ...route }

        if (hasPermission(permissions, tempRoute.meta?.permissions)) {
            if (tempRoute.children) {
                tempRoute.children = filterAsyncRoutes(tempRoute.children, permissions)
            }
            filteredRoutes.push(tempRoute)
        }
    })

    return filteredRoutes
}

// 检查权限
const hasPermission = (userPermissions: string[], routePermissions?: string[]): boolean => {
    if (!routePermissions || routePermissions.length === 0) {
        return true
    }

    return routePermissions.some(permission => userPermissions.includes(permission))
}

// 记录是否已经添加过动态路由
let hasAddRoutes = false

// 路由守卫
router.beforeEach(async (to, from, next) => {
    const token = getToken()
    const userStore = useUserStore()

    if (to.path === '/login') {
        if (token) {
            next('/')
        } else {
            next()
        }
    } else {
        if (!token) {
            // 重置路由状态
            hasAddRoutes = false
            next('/login')
        } else {
            if (!userStore.user) {
                try {
                    await userStore.getUserInfoAction()
                    if (!hasAddRoutes) {
                        addAsyncRoutes(userStore.userPermissions)
                        hasAddRoutes = true
                        next({ ...to, replace: true })
                    } else {
                        next()
                    }
                } catch (error) {
                    hasAddRoutes = false
                    await userStore.logoutAction()
                    next('/login')
                }
            } else {
                if (!hasAddRoutes) {
                    addAsyncRoutes(userStore.userPermissions)
                    hasAddRoutes = true
                    next({ ...to, replace: true })
                } else {
                    next()
                }
            }
        }
    }
})

export default router 